package com.zhangyang.dubbo.order;

import com.zhangyang.dubbo.IUserService;
import com.zhangyang.dubbo.OrderService;
import com.zhangyang.dubbo.RequestCode;
import com.zhangyang.dubbo.ResponseCode;
import com.zhangyang.dubbo.dal.OrderDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.jta.JtaTransactionManager;

import javax.transaction.NotSupportedException;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;

/**
 *  Created by zhangyang on 2017/8/30.
 *  主要负责业务的处理
 */
@Service(value = "orderService")
public class OrderServiceImpl  implements OrderService {

    @Autowired
    JtaTransactionManager springTransactionManager;//spring中事务实例

    @Autowired
    OrderDao orderDao;

    @Autowired
    IUserService userService;

    public OrderServiceImpl() {
    }

    /**
     * 取消订单
     * @param requestCode
     * @return
     */
    public ResponseCode doOrder(RequestCode requestCode){
        System.out.println("OrderServiceImpl ..曾经来过");
        ResponseCode responseCode=new ResponseCode();
        //order下单后 进行更新余额
        UserTransaction userTransaction=springTransactionManager.getUserTransaction();
        try {
            userTransaction.begin();
            orderDao.insertOrder();
            userService.debet(2000,"zhangyang",1);
            userTransaction.commit();
            responseCode.setCode(10001);
            responseCode.setId("1234567890");
            responseCode.setMsg("访问成功!");
        } catch (Exception e) {
            try {
                e.printStackTrace();
                responseCode.setCode(500);
                responseCode.setId("1234567890");
                responseCode.setMsg("访问失败!");
                userTransaction.rollback();//进行回滚
            } catch (SystemException e1) {
                e1.printStackTrace();
            }
        }
        return responseCode;
    }

    /**
     * 取消订单
     * @param requestCode
     * @return
     */
    public ResponseCode cancelOrder(RequestCode requestCode) {
        System.out.println("OrderServiceImpl ..cancelOrder 取消订单 曾经来过");
        ResponseCode responseCode=new ResponseCode();
        responseCode.setCode(10002);
        responseCode.setId("88888888888");
        responseCode.setMsg("取消订单访问成功!");
        return responseCode;
    }
}
